package kafkaTest;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.Random;

/**
 * All rights Reserved, Designed By www.tusdao.com
 *
 * @version V1.0
 * @Title: KafkaTest01
 * @Package myTest
 * @Description: kafka生产者
 * @author: tusxxw
 * @date: 2021/2/18
 * @Copyright: 2020 www.tbs.com Inc. All rights reserved.
 * <p>
 * 注意：本内容仅限于TBS项目组内部传阅，禁止外泄以及用于其他的商业目的
 */
public class KafkaProductor {
    public static String TOPIC = "topic_opt_conf";//定义主题

    public static void main(String[] args) throws InterruptedException {
        //简单的配置信息
        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.1.214:9092");//kafka地址，多个地址用逗号分割
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(p);

        try {
            //开始愉快的发消息
            for (int i = 0; i < 100; i++) {
                String msg = "test," + new Random().nextInt(100);
                ProducerRecord<String, String> record = new ProducerRecord<String, String>(TOPIC, msg);
                kafkaProducer.send(record);
                System.out.println("消息发送成功:" + msg);
                Thread.sleep(500);
            }
        } finally {
            kafkaProducer.close();
        }

    }

}
